package com.jmm.common.shiro;

import cn.hutool.core.util.StrUtil;
import com.jmm.common.constant.ApiRoleConstants;
import com.jmm.common.utils.ShiroUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;

/**
 * <pre>
 * </pre>
 * <small> 2018年4月22日 |  </small>
 */
@Service
public class JWTAuthorizingRealm extends AuthorizingRealm {

    @Override
    public String getName() {
        return "apiRealm";
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTAuthenticationTokenToken;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //TODO 校验客户经理 添加客户经理角色
        String userId = ShiroUtils.getUserId();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if(StrUtil.isEmpty(userId)){
            simpleAuthorizationInfo.addRole(ApiRoleConstants.USER);
            return simpleAuthorizationInfo;
        }
        /**
         * 查询客户经理
         */
        /*AccountManagerDo managerDo = new UmsAccountManagerDo();
        managerDo.setUserId(userId);
        AccountManagerDo accountManagerDo = umsAccountManagerMapper.selectOne(new QueryWrapper<>(managerDo));*/
        if(null != null){
            simpleAuthorizationInfo.addRole(ApiRoleConstants.MANAGER);
        }
        simpleAuthorizationInfo.addRole(ApiRoleConstants.USER);
        return simpleAuthorizationInfo;
    }

    /**
     * 身份认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}
